package monitor

import (
	"net/http"
	"github.com/gorilla/websocket"
	"log"
)

func Init() {
	http.HandleFunc("/ws", ws)
	err := http.ListenAndServe(":8099", nil)
	if err != nil {
		log.Print("websocket创建失败")
	}
}

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

var clients = map[int]*websocket.Conn{}
var count = 0

func ws(w http.ResponseWriter, r *http.Request) {
	client, _ := upgrader.Upgrade(w, r, nil)
	count++
	clients[count] = client
	print(count)

	defer client.Close()
	for {
		mt, message, _ := client.ReadMessage()
		client.WriteMessage(mt, message)
	}
}

type Message struct {
	Type    string `json:"type"`
	Name    string `json:"name"`
	Content string `json:"content"`
}

func Send(name string, message string) {

	for _, v := range clients {
		v.WriteJSON(Message{
			Name:    name,
			Content: message,
		})
	}
}
